{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-03-07T02:01:46.629300Z",
     "start_time": "2024-03-07T02:01:45.457582Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "     daily_return\n0        0.996043\n1        1.011158\n2        1.000654\n3        1.024586\n4        1.024829\n..            ...\n244      1.131925\n245      1.145605\n246      1.149507\n247      1.156335\n248      1.157630\n\n[249 rows x 1 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>daily_return</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.996043</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1.011158</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1.000654</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1.024586</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1.024829</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>244</th>\n      <td>1.131925</td>\n    </tr>\n    <tr>\n      <th>245</th>\n      <td>1.145605</td>\n    </tr>\n    <tr>\n      <th>246</th>\n      <td>1.149507</td>\n    </tr>\n    <tr>\n      <th>247</th>\n      <td>1.156335</td>\n    </tr>\n    <tr>\n      <th>248</th>\n      <td>1.157630</td>\n    </tr>\n  </tbody>\n</table>\n<p>249 rows × 1 columns</p>\n</div>"
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stock = 'sp500'\n",
    "df = pd.read_csv(f\"{stock}_output/3return.csv\")\n",
    "df.columns = ['index', 'daily_return']\n",
    "pred = df[['daily_return']]\n",
    "pred"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T02:01:46.707111Z",
     "start_time": "2024-03-07T02:01:46.631962Z"
    }
   },
   "id": "2d2ea121462c9fc0",
   "execution_count": 2
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "pred.to_csv(f'{stock}.csv', index=None)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T02:01:46.740360Z",
     "start_time": "2024-03-07T02:01:46.709270Z"
    }
   },
   "id": "22402b8d2afa60e8",
   "execution_count": 3
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\胡逸凡\\AppData\\Local\\Temp\\ipykernel_14528\\490373256.py:1: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  pred['daily_return'] = pred['daily_return'] / pred['daily_return'].shift(1)\n",
      "C:\\Users\\胡逸凡\\AppData\\Local\\Temp\\ipykernel_14528\\490373256.py:2: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  pred['daily_return'] = pred['daily_return'] - 1\n",
      "C:\\Users\\胡逸凡\\AppData\\Local\\Temp\\ipykernel_14528\\490373256.py:3: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  pred.dropna(inplace=True)\n"
     ]
    }
   ],
   "source": [
    "pred['daily_return'] = pred['daily_return'] / pred['daily_return'].shift(1)\n",
    "pred['daily_return'] = pred['daily_return'] - 1\n",
    "pred.dropna(inplace=True)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T02:01:46.775016Z",
     "start_time": "2024-03-07T02:01:46.746408Z"
    }
   },
   "id": "adef6b4ed9a40951",
   "execution_count": 4
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "     daily_return\n1        0.015175\n2       -0.010388\n3        0.023916\n4        0.000238\n5        0.007287\n..            ...\n244     -0.016803\n245      0.012085\n246      0.003406\n247      0.005940\n248      0.001120\n\n[248 rows x 1 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>daily_return</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>0.015175</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-0.010388</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.023916</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.000238</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0.007287</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>244</th>\n      <td>-0.016803</td>\n    </tr>\n    <tr>\n      <th>245</th>\n      <td>0.012085</td>\n    </tr>\n    <tr>\n      <th>246</th>\n      <td>0.003406</td>\n    </tr>\n    <tr>\n      <th>247</th>\n      <td>0.005940</td>\n    </tr>\n    <tr>\n      <th>248</th>\n      <td>0.001120</td>\n    </tr>\n  </tbody>\n</table>\n<p>248 rows × 1 columns</p>\n</div>"
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pred"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T02:01:46.818693Z",
     "start_time": "2024-03-07T02:01:46.783017Z"
    }
   },
   "id": "62f92ec5bbd50327",
   "execution_count": 5
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "portfolio_df_performance = pred"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T02:01:46.865501Z",
     "start_time": "2024-03-07T02:01:46.822257Z"
    }
   },
   "id": "eae8b2857438ddaa",
   "execution_count": 6
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\胡逸凡\\AppData\\Local\\Temp\\ipykernel_14528\\980728215.py:12: FutureWarning: 'm' is deprecated and will be removed in a future version, please use 'ME' instead.\n",
      "  monthly_statistics_df = alpha_df_performance[net_value_columns].resample('m').last()\n",
      "C:\\Users\\胡逸凡\\AppData\\Local\\Temp\\ipykernel_14528\\980728215.py:20: FutureWarning: 'y' is deprecated and will be removed in a future version, please use 'YE' instead.\n",
      "  yearly_statistics_df = alpha_df_performance[net_value_columns].resample('y').last()\n",
      "C:\\Users\\胡逸凡\\AppData\\Roaming\\Python\\Python310\\site-packages\\numpy\\core\\fromnumeric.py:3643: FutureWarning: The behavior of DataFrame.std with axis=None is deprecated, in a future version this will reduce over both axes and return a scalar. To retain the old behavior, pass axis=0 (or do not pass axis)\n",
      "  return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)\n",
      "C:\\Users\\胡逸凡\\AppData\\Roaming\\Python\\Python310\\site-packages\\numpy\\core\\fromnumeric.py:3643: FutureWarning: The behavior of DataFrame.std with axis=None is deprecated, in a future version this will reduce over both axes and return a scalar. To retain the old behavior, pass axis=0 (or do not pass axis)\n",
      "  return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)\n",
      "C:\\Users\\胡逸凡\\AppData\\Roaming\\Python\\Python310\\site-packages\\numpy\\core\\fromnumeric.py:3643: FutureWarning: The behavior of DataFrame.std with axis=None is deprecated, in a future version this will reduce over both axes and return a scalar. To retain the old behavior, pass axis=0 (or do not pass axis)\n",
      "  return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)\n"
     ]
    }
   ],
   "source": [
    "alpha_df_performance = pd.DataFrame()\n",
    "alpha_df_performance['portfolio_daily_return'] = portfolio_df_performance['daily_return']\n",
    "alpha_df_performance['portfolio_net_value'] = (alpha_df_performance['portfolio_daily_return'] + 1).cumprod()\n",
    "\n",
    "net_value_columns = ['portfolio_net_value']\n",
    "\n",
    "alpha_statistics_df = pd.DataFrame(index=alpha_df_performance[net_value_columns].columns,\n",
    "                                    columns=[\"年化收益\", \"年化波动率\", \"最大回撤率\", \"夏普率\", \"Calmar\", \"IR\"])\n",
    "\n",
    "# alpha_df_performance.set_index(\"dt\", inplace=True)\n",
    "alpha_df_performance.index = pd.to_datetime(alpha_df_performance.index)\n",
    "monthly_statistics_df = alpha_df_performance[net_value_columns].resample('m').last()\n",
    "monthly_statistics_df = pd.concat([alpha_df_performance[:1][\n",
    "                                        ['portfolio_net_value']],\n",
    "                                    monthly_statistics_df])\n",
    "monthly_statistics_df = monthly_statistics_df.pct_change()\n",
    "monthly_statistics_df = monthly_statistics_df.dropna()\n",
    "monthly_statistics_df.index = monthly_statistics_df.index.date\n",
    "## TODO 补充第一年的数据\n",
    "yearly_statistics_df = alpha_df_performance[net_value_columns].resample('y').last()\n",
    "yearly_statistics_df = pd.concat([alpha_df_performance[:1][\n",
    "                                        ['portfolio_net_value']],\n",
    "                                    yearly_statistics_df])\n",
    "yearly_statistics_df = yearly_statistics_df.pct_change()\n",
    "yearly_statistics_df = yearly_statistics_df.dropna()\n",
    "yearly_statistics_df.index = yearly_statistics_df.index.date\n",
    "\n",
    "alpha_statistics_df.loc[:, \"年化收益\"] = np.mean(\n",
    "    (alpha_df_performance[net_value_columns].tail(1)) ** (252 / len(alpha_df_performance)) - 1)\n",
    "alpha_statistics_df.loc[:, \"年化波动率\"] = np.std(\n",
    "    alpha_df_performance[net_value_columns] / alpha_df_performance[net_value_columns].shift(1) - 1) * np.sqrt(\n",
    "    252)\n",
    "alpha_statistics_df.loc[:, \"累积收益\"] = np.mean(alpha_df_performance[net_value_columns].tail(1) - 1)\n",
    "alpha_statistics_df.loc[:, \"累积波动率\"] = np.std(\n",
    "    alpha_df_performance[net_value_columns] / alpha_df_performance[net_value_columns].shift(1) - 1)\n",
    "alpha_statistics_df.loc[:, \"最大回撤率\"] = np.min(\n",
    "    (alpha_df_performance[net_value_columns] - alpha_df_performance[net_value_columns].cummax()) /\n",
    "    alpha_df_performance[net_value_columns].cummax())\n",
    "alpha_statistics_df.loc[:, \"夏普率\"] = alpha_statistics_df[\"年化收益\"] / alpha_statistics_df[\"年化波动率\"]\n",
    "alpha_statistics_df.loc[:, \"Calmar\"] = alpha_statistics_df[\"年化收益\"] / abs(alpha_statistics_df[\"最大回撤率\"])\n",
    "alpha_statistics_df.loc[:, \"IR\"] = np.mean(\n",
    "    alpha_df_performance[net_value_columns] / alpha_df_performance[net_value_columns].shift(1) - 1) * np.sqrt(\n",
    "    252) / np.std(alpha_df_performance[net_value_columns] / alpha_df_performance[net_value_columns].shift(1) - 1)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T02:01:46.990759Z",
     "start_time": "2024-03-07T02:01:46.867556Z"
    }
   },
   "id": "ce7acf6b5cb7b248",
   "execution_count": 7
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "                        年化收益     年化波动率     最大回撤率       夏普率    Calmar       IR  \\\nportfolio_net_value  0.16505  0.141625 -0.125878  1.165406  1.311196  1.04555   \n\n                         累积收益     累积波动率  \nportfolio_net_value  0.162229  0.008922  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>年化收益</th>\n      <th>年化波动率</th>\n      <th>最大回撤率</th>\n      <th>夏普率</th>\n      <th>Calmar</th>\n      <th>IR</th>\n      <th>累积收益</th>\n      <th>累积波动率</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>portfolio_net_value</th>\n      <td>0.16505</td>\n      <td>0.141625</td>\n      <td>-0.125878</td>\n      <td>1.165406</td>\n      <td>1.311196</td>\n      <td>1.04555</td>\n      <td>0.162229</td>\n      <td>0.008922</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alpha_statistics_df"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T02:01:47.006790Z",
     "start_time": "2024-03-07T02:01:46.994760Z"
    }
   },
   "id": "a520d5a5b89e260",
   "execution_count": 8
  },
  {
   "cell_type": "markdown",
   "source": [
    "DeepPocket\n",
    "ASR = ARR / AVol;   CR = ARR / abs(MDD)\n",
    "        ARR    AVol    MDD    ASR    CR    IR\n",
    "hs300 -0.036  0.135  -0.175 -0.270 -0.207 -0.258\n",
    "\n",
    "zz500  0.006  0.127  -0.148  0.050  0.043  0.115\n",
    "\n",
    "sp500  0.165  0.142  -0.126  1.165  1.311  1.045\n",
    "   \n",
    "nas100 0.346  0.157  -0.116  2.197  2.971  1.882"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "de4b1bdfc542b0c"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
